//
//  CenterViewController.swift
//  ZCF
//
//  Created by 赵世杰 on 16/3/15.
//  Copyright © 2016年 zhaoshijie. All rights reserved.
//

import UIKit
import Foundation


//let KScreenWidth = UIScreen.mainScreen().bounds.size.width
//let KScreenHeight = UIScreen.mainScreen().bounds.size.height

enum PullState {
    // 下拉刷新
    case dropDown
    // 上拉加载
    case pullOn
}


class CenterViewController: BaseViewController,UIScrollViewDelegate,UITableViewDataSource,UITableViewDelegate,UISearchBarDelegate{
    
    
    /// 变量
    
    // 头部数据
    var headViewDataList:Array<AnyObject>!
    // 项目列表数据
    var projectList:Array<AnyObject>!
    // button的图片文字
    var buttonTitleArray:Array<String>!
    // 刷新界面的页数
    var indexPages:Int!

    
    /// 试图
    
    // 头部图片切换视图
    var headView:UIView!
    var scrollerView:UIScrollView!
    var pageControl:UIPageControl!
    var searchBar:UISearchBar!
    
    
    
    @IBOutlet var overallTableView: UITableView!
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.navigationController?.navigationBar.isHidden = true
        // 设置导航栏透明
        self.automaticallyAdjustsScrollViewInsets = false
        
        
        // 检查网络状态
        let reachabilityManager = AFNetworkReachabilityManager.shared() as AFNetworkReachabilityManager
        reachabilityManager.startMonitoring()
        reachabilityManager.setReachabilityStatusChange { (statu:AFNetworkReachabilityStatus) -> Void in
            switch statu
            {
            case .unknown:
                print("未知")
                break
            case .notReachable:
                print("没有网络")
                
                let alertC = UIAlertController(title: "没有网络", message: "请检查网络连接", preferredStyle: UIAlertControllerStyle.alert)
                let action = UIAlertAction(title: "确定", style: UIAlertActionStyle.default, handler: { (action:UIAlertAction) -> Void in
                    return
                })
                alertC.addAction(action)
                self .present(alertC, animated: true, completion: nil)
                break
            case .reachableViaWWAN:
                print("3G|4G")
                break
            case .reachableViaWiFi:
                print("wifi")
                break
                
            }
        };
        
        // 初始化数据
        self._initDataList()
        
        
        // 创建视图
        self._initViews()
        
        // 数据加载
        self.requestDataList()
    }
    
    
    /**
     初始化数据
     */
    func _initDataList()
    {
        
        self.headViewDataList = Array<AnyObject>()
        self.projectList = Array<AnyObject>()
        self.indexPages = 0
        
        self.buttonTitleArray = ["积分兑换","热销榜单","他们说","众筹攻略"]
    }
    
    /**
     创建视图
     */
    func _initViews()
    {
        
        self.overallTableView.delegate = self
        self.overallTableView.dataSource = self
        
        //  添加上拉加载下拉刷新
        self.overallTableView.addHeader(withTarget: self, action:#selector(CenterViewController.refreshHeaderAction))
        self.overallTableView.addFooter(withTarget: self, action:#selector(CenterViewController.refreshFooterAction))
        
        
        // 创建头试图
        self._headScrollerView()
        
        
        // 注册单元格
        self.overallTableView.register(UINib(nibName: "ProjectTableViewCell", bundle: nil), forCellReuseIdentifier:"cellID2")
    }
    
    /**
     创建头试图
     */
    func _headScrollerView()
    {
        self.headView = UIView(frame: CGRect(x: 0, y: 0, width: KScreenWidth, height: 200+20))
        self.headView.backgroundColor = UIColor ( red: 0.9046, green: 0.8999, blue: 0.9093, alpha: 1.0 )
        
        // 滑动视图
        self.scrollerView = UIScrollView(frame: CGRect(x: 0, y: 0, width: KScreenWidth, height: 200))
        self.scrollerView.isPagingEnabled = true
        self.scrollerView.delegate = self
        self.scrollerView.showsHorizontalScrollIndicator = false
        self.headView.addSubview(scrollerView)
        
        self.pageControl = UIPageControl(frame: CGRect(x: 0, y: 200-20-15, width: KScreenWidth, height: 20))
        self.headView.addSubview(pageControl)
        
        
        self.searchBar = UISearchBar(frame: CGRect(x: 20, y: 200-15, width: KScreenWidth-40, height: 30))
//        self.searchBar.layer.cornerRadius = 4
//        self.searchBar.layer.masksToBounds = true
        self.searchBar.backgroundImage = self.imageWithColor(UIColor.clear)
        self.searchBar.placeholder = "请输入项目名称"
        self.searchBar.delegate = self
        self.headView.addSubview(self.searchBar)
        
        overallTableView.tableHeaderView = self.headView
        
    }
    
    func imageWithColor(_ color:UIColor) -> (UIImage)
    {
        let rect = CGRect(x: 0.0, y: 0.0, width: 1.0, height: 1.0)
        UIGraphicsBeginImageContext(rect.size)
        let context = UIGraphicsGetCurrentContext()
        context?.setFillColor(color.cgColor)
        context?.fill(rect)
        
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image!
    }
    
    /**
     请求成功之后需要更新的方法
     */
    func _requestSuccessNext()
    {
        self.scrollerView.contentSize = CGSize(width: KScreenWidth*CGFloat(headViewDataList.count), height: 200)
        // 滑动视图上面的图片视图
        for i in 0  ..< headViewDataList.count 
        {
            let scrollerViewImage = UIImageView(frame:CGRect(x: KScreenWidth*CGFloat(i), y: 0, width: KScreenWidth, height: 200))
            self.scrollerView.addSubview(scrollerViewImage)
            // 获取数据
            let headScrollerModel = headViewDataList[i] as! HeadScrollerModel
            scrollerViewImage.SJ_setImageWithUrlString(headScrollerModel.url)
        }
        self.pageControl.numberOfPages = headViewDataList.count
        
        self.headView .bringSubview(toFront: self.searchBar)
    }
    
    //MARK: - 数据请求
    func requestDataList()
    {
        // 请求表头数据
        self .requestHeadScroller()
        
        // 请求项目列表数据
        self .requestProjectList(PullState.dropDown)
        
        
    }
    
    
    /**
     请求表头数据
     */
    func requestHeadScroller()
    {
        headViewDataList = Array<AnyObject>()
//        let urlString = HttpUrl + "/banner/image/get"
//        
//        let manager = AFHTTPRequestOperationManager()
//        manager.requestSerializer.setValue("2.0", forHTTPHeaderField: "version")
//        manager.requestSerializer.setValue("ios", forHTTPHeaderField: "terminal")
//        manager.post(urlString, parameters: nil, success: { (operation:AFHTTPRequestOperation？, responseObject:AnyObject？) -> Void in
////            print("请求成功") ;
//            print(responseObject["data"]) ;
//            let data:Array<AnyObject> = responseObject["data"] as! Array
//            for dic:AnyObject in data
//            {
//                let headScrollerModel = HeadScrollerModel()
//                headScrollerModel.initWithDictionary(dic)
//                self.headViewDataList.append(headScrollerModel)
//            }
//
//            // 刷新
//            self._requestSuccessNext()
//            
//            
//            }) { (operation:AFHTTPRequestOperation!, error:NSError!) -> Void in
////                print("请求失败") ;
//        }
        
        let urlString = HttpUrl + "/bbs/banner/image/get"
        let requestHeader:[String:String] = ["version":"2.0","terminal":"ios"]
        let request = HTTPRequest()
        request.POSTRequest(urlString, httpHeader: requestHeader, parameters: nil, resultBlock: { (result) -> Void in
            print("请求成功")

//            print(result["data"]) ;
            let data:Array<AnyObject> = result["data"] as! Array
            for dic:AnyObject in data
            {
                let headScrollerModel = HeadScrollerModel()
                headScrollerModel.initWithDictionary(dic)
                self.headViewDataList.append(headScrollerModel)
            }
            
            // 刷新
            self._requestSuccessNext()
            
        }) { () -> Void in
            //                print("请求失败")
        }

    }
    
    /**
     请求项目列表数据
     */
    func requestProjectList(_ state:PullState)
    {
        let urlString = HttpUrl + "/project/list/condition"
        let httpHeader:[String:String] = ["version":"2.0","terminal":"ios"]
        let httpRequest = HTTPRequest()
        var parameterDic:Dictionary<String,String> = Dictionary()
        // 判断是下拉
        if state == PullState.pullOn
        {
            parameterDic = ["homeShow":String(1) , "page":String(self.indexPages)]
            
        }
        httpRequest.POSTRequest(urlString, httpHeader: httpHeader, parameters: parameterDic, resultBlock: { (result) -> Void in
            print("%@",result)
            
            if state == PullState.dropDown
            {
                self.projectList.removeAll()
                self.indexPages = 0
            }
            else if state == PullState.pullOn
            {
                self.indexPages = self.indexPages + 1
            }
            
            let data:Dictionary<String,AnyObject> = result["data"] as! Dictionary
            let list:Array<AnyObject> = data["list"] as! Array
            for dic:AnyObject in list
            {
                let projectListModel = ProjectListModel()
                projectListModel.initWithDictionary(dic)
                self.projectList .append(projectListModel)
            }
            self.overallTableView .reloadData()
            // 关闭刷新
            self .endTableViewRefreshing()
            }) { () -> Void in
//                print("请求失败")
        }
        
    }
    
    //MARK: - 关闭刷新效果
    func endTableViewRefreshing()
    {
        if self.overallTableView.isHeaderRefreshing
        {
            self.overallTableView.headerEndRefreshing()
        }
        else if self.overallTableView.isFooterRefreshing
        {
            self.overallTableView.footerEndRefreshing()
        }
    }
    
    
    //MARK: - 上拉刷新下拉加载的响应事件
    func refreshHeaderAction()
    {
        // 请求项目列表数据
        self .requestProjectList(PullState.dropDown)
    }
    
    func refreshFooterAction()
    {
//        self.requestProjectList(PullState.PullOn)
        // 关闭刷新效果
//        self.endTableViewRefreshing()
        self.overallTableView.footerEndRefreshing()
    }
    
    
    //MARK: - scrollView的代理方法
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        let pageIndex = self.scrollerView.contentOffset.x / KScreenWidth
        self.pageControl.currentPage = NSInteger(pageIndex)
    }
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        if(decelerate == false)
        {
            let pageIndex = self.scrollerView.contentOffset.x / KScreenWidth
            self.pageControl.currentPage = NSInteger(pageIndex)
        }
    }
    
    
    //MARK: -  点击事件
//    func buttonAction(sender:UIButton)
//    {
//        if sender.tag == 100
//        {
//            self.tabBarController?.selectedIndex = 1
//        }
//        else if sender.tag == 101
//        {
//            self.tabBarController?.selectedIndex = 3
//        }
//        else if sender.tag == 102
//        {
//            self.tabBarController?.selectedIndex = 0
//        }
//        else if sender.tag == 103
//        {
//            
//        }
//    }
    
    //MARK: - tableView的代理方法
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.projectList.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        if((indexPath as NSIndexPath).row == 0)
        {
            let cellID = "cellID1"
            var cell = tableView.dequeueReusableCell(withIdentifier: cellID)
            if(cell == nil)
            {
                cell = UITableViewCell(style: .default, reuseIdentifier: cellID)
                cell?.selectionStyle = .none
                cell!.contentView.backgroundColor = UIColor ( red: 0.9046, green: 0.8999, blue: 0.9093, alpha: 1.0 )
                
                
                let view = UIView(frame: CGRect(x: 5, y: 0, width: KScreenWidth-10, height: (KScreenWidth-80)/4.0+30))
                view.backgroundColor = UIColor.white
                cell?.contentView.addSubview(view)
                
                for i in 0  ..< 4 
                {
                    
                    // 创建button
                    let width = 10+((KScreenWidth-90)/4.0+20)*CGFloat(i)
                    let button = UIButton(type: .custom)
                    button.frame = CGRect(x: width, y: 5, width: (KScreenWidth-90)/4.0, height: (KScreenWidth-90)/4.0)
                    button.tag = 100 + i
                    button.setTitle(self.buttonTitleArray[i], for: UIControlState())
                    let imageName = "zc_menu_" + String(i+1)
                    button.setImage(UIImage(named: imageName), for: UIControlState())
                    button.addTarget(self, action: Selector(("buttonAction:")), for: .touchUpInside)
                    view.addSubview(button)
                    
                    // 创建Lable
                    let label = UILabel(frame: CGRect(x: width, y: (KScreenWidth-80)/4.0, width: (KScreenWidth-80)/4.0, height: 20))
                    label.textColor = UIColor.gray
                    label.font = UIFont .systemFont(ofSize: 12)
                    label.text = self.buttonTitleArray[i]
                    label.textAlignment = .center
                    view.addSubview(label)
                }
            }
            return cell!
        }
        else
        {
            let cellID = "cellID2"
            let cell = tableView.dequeueReusableCell(withIdentifier: cellID) as! ProjectTableViewCell
            // 获取这个单元格的数据
            let projectListModel = projectList[(indexPath as NSIndexPath).row] as! ProjectListModel
            cell.projectCellImageString = projectListModel.listImageUrl
            cell.textString = projectListModel.label
            cell.startMoney = projectListModel.amount
            cell.targetNumber = projectListModel.targetNum
            cell.selectionStyle = .none
            return cell

        }
        
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if((indexPath as NSIndexPath).row == 0)
        {
            return (KScreenWidth-80)/4.0+30
        }
        else
        {
            return 200
        }
    }
    
}
